//
//  DetailKindController.m
//  MarianasTrench
//
//  Created by 王晓晨 on 16/3/17.
//  Copyright © 2016年 王爵. All rights reserved.
//

#import "DetailKindController.h"

@interface DetailKindController ()<UICollectionViewDataSource, UICollectionViewDelegate, BigDetailKindControllerDelegate, bigDetailKindOtherDelegate, UICollectionViewDelegateFlowLayout>

@property (nonatomic, strong) UICollectionView *navigateCollection;/**< 导航collection >*/
@property (nonatomic, strong) UICollectionView *bigCollection;/**< 主页collection >*/

@property (nonatomic, strong) NSMutableArray *navigateArr;/**< 导航Model数组 >*/
@property (nonatomic, strong) NSMutableArray *navigateTitleArr;/**< 带推荐model数组 >*/
@property (nonatomic, strong) NSMutableArray *arrModel;/**< Cell的Model >*/
@property (nonatomic, strong) NSMutableArray *picArr;/**< 轮播图数组 >*/
@property (nonatomic, strong) NSMutableArray *topArr;/**< 每日top50 >*/
@property (nonatomic, assign) NSInteger currentIndex;/**< bigCollection偏移量 >*/
@property (nonatomic, strong) UIView *moreView;/**< 更多页面 >*/
@property (nonatomic, strong) UICollectionView *moreCollection;/**< 更多页面collection >*/
@property (nonatomic, assign) BOOL buttonState;/**< 更多按钮状态 >*/
@property (nonatomic, assign) NSInteger moreCurrentIndex;/**< 更多也bigcollection偏移量 >*/

@end

@implementation DetailKindController



-(void)dealloc{
    [_bigCollection removeObserver:self forKeyPath:@"contentOffset"];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.title = self.titleName;
    self.view.backgroundColor = [UIColor whiteColor];
    
    
    self.navigateArr = [NSMutableArray array];
    MoreDetailKindModel *model = [[MoreDetailKindModel alloc] init];
    model.tname = @"推荐";
    self.navigateTitleArr = [NSMutableArray arrayWithObjects:model, nil];
    
    self.arrModel = [NSMutableArray array];
    self.picArr = [NSMutableArray array];
    self.topArr = [NSMutableArray array];
    
    /** 返回按钮 */
    UIBarButtonItem *backItme = [[UIBarButtonItem alloc] initWithImage:ORIGIMAGE(@"icon_back_h@2x.png") style:UIBarButtonItemStyleDone target:self action:@selector(backItemAction:)];
    self.navigationItem.leftBarButtonItem = backItme;
    
    [self dataHandel];
}

- (void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.hidden = NO;
}


#pragma mark - 创建子视图
- (void)createSubViews {
    
    /** 导航栏collection */
    UICollectionViewFlowLayout *naviLayout = [[UICollectionViewFlowLayout alloc] init];
    naviLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    naviLayout.itemSize = CGSizeMake((SCREEN_WIDTH) / 4, 40);
    naviLayout.minimumInteritemSpacing = 0;
    naviLayout.minimumLineSpacing = 0;
    naviLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    
    self.navigateCollection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH - 81, 40) collectionViewLayout:naviLayout];
    [self.view addSubview:_navigateCollection];
    _navigateCollection.backgroundColor = RGBA(233, 231, 228, 1);
    _navigateCollection.delegate = self;
    _navigateCollection.dataSource = self;
    [_navigateCollection registerClass:[DetailKindNavigateCollectionCell class] forCellWithReuseIdentifier:@"DetailKindNavigateCollectionCell"];
    
    /** 主页面显示Collection */
    UICollectionViewFlowLayout *bigLayout = [[UICollectionViewFlowLayout alloc] init];
    bigLayout.itemSize = CGSizeMake(SCREEN_WIDTH, SCREEN_HETGHT - 153);
    bigLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    bigLayout.minimumInteritemSpacing = 0;
    bigLayout.minimumLineSpacing = 0;
    bigLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    
    self.bigCollection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 40, SCREEN_WIDTH, SCREEN_HETGHT - 153) collectionViewLayout:bigLayout];
    [self.view addSubview:_bigCollection];
    _bigCollection.pagingEnabled = YES;
    _bigCollection.delegate = self;
    _bigCollection.dataSource = self;
    _bigCollection.backgroundColor = RGBA(233, 231, 228, 1);
    [_bigCollection registerClass:[BigDetailKindCollectionCell class] forCellWithReuseIdentifier:@"BigDetailKindCollectionCell"];
    [_bigCollection registerClass:[BIgDetailKindCollectOtherCell class] forCellWithReuseIdentifier:@"BIgDetailKindCollectOtherCell"];
    
    [_bigCollection addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
    
    /** 更多按钮 */
    UIButton *moreButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [moreButton setTitle:@"更多🔻" forState:UIControlStateNormal];
    moreButton.backgroundColor = RGBA(233, 231, 228, 1);
    moreButton.frame = CGRectMake(SCREEN_WIDTH - 80, 0, 80, 40);
    moreButton.showsTouchWhenHighlighted = YES;
    moreButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [moreButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.view addSubview:moreButton];
    [moreButton addTarget:self action:@selector(moreButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    self.buttonState = NO;
}

#pragma mark - button点击放啊
- (void)backItemAction:(UIBarButtonItem *)item {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)moreButtonAction:(UIButton *)button {
    if (_buttonState == NO) {
        [UIView animateWithDuration:0.3 animations:^{
            _moreView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HETGHT - 113);
        }];
    }
    self.buttonState = !_buttonState;
}

#pragma mark - 更多页面View
- (void)createMoreView {
    self.moreView = [[UIView alloc] initWithFrame:CGRectMake(0, - SCREEN_HETGHT, SCREEN_WIDTH, SCREEN_HETGHT - 113)];
    [self.view addSubview:_moreView];
    _moreView.backgroundColor = RGBA(233, 231, 228, 1);
    
    UILabel *infoLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH / 2, 40)];
    infoLabel.text = @"    请选择类别/筛选";
    [self.moreView addSubview:infoLabel];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake((SCREEN_WIDTH - 4) / 3, 38);
    layout.minimumInteritemSpacing = 1;
    layout.minimumLineSpacing = 1;
    layout.sectionInset = UIEdgeInsetsMake(1, 1, 1, 1);
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    self.moreCollection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 40, SCREEN_WIDTH, SCREEN_HETGHT - 200) collectionViewLayout:layout];
    [self.moreView addSubview:_moreCollection];
    _moreCollection.backgroundColor = RGBA(233, 231, 228, 1);
    _moreCollection.delegate = self;
    _moreCollection.dataSource = self;
    
    [_moreCollection registerClass:[SmallDetailKindCollectionCellS class] forCellWithReuseIdentifier:@"SmallDetailKindCollectionCellS"];
    [_moreCollection registerClass:[BigDetailKindHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"BigDetailKindHeaderView"];
    
    UIButton *collectButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [collectButton setTitle:@"收起🔺" forState:UIControlStateNormal];
    collectButton.frame = CGRectMake(SCREEN_WIDTH - 80, 0, 80, 40);
    collectButton.backgroundColor = RGBA(233, 231, 228, 1);
    collectButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [collectButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    collectButton.showsTouchWhenHighlighted = YES;
    [_moreView addSubview:collectButton];
    [collectButton addTarget:self action:@selector(collectButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *finishButton = [UIButton buttonWithType:UIButtonTypeCustom];
    finishButton.frame = CGRectMake((SCREEN_WIDTH - (SCREEN_WIDTH / 7)) / 2, SCREEN_HETGHT - (SCREEN_WIDTH / 7) - 180, SCREEN_WIDTH / 7, SCREEN_WIDTH / 7);
    finishButton.layer.cornerRadius = SCREEN_WIDTH / 14;
    finishButton.layer.masksToBounds = YES;
    finishButton.showsTouchWhenHighlighted = YES;
    [finishButton setTitle:@"完成" forState:UIControlStateNormal];
    finishButton.backgroundColor = [UIColor redColor];
    [_moreView addSubview:finishButton];
    [finishButton addTarget:self action:@selector(collectButtonAction:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)collectButtonAction:(UIButton *)button {
    if (_buttonState == YES) {
        [UIView animateWithDuration:0.3 animations:^{
            _moreView.frame = CGRectMake(0, - SCREEN_HETGHT, SCREEN_WIDTH, SCREEN_HETGHT - 113);
        }];
    }
    self.buttonState = !_buttonState;
}


#pragma mark - 返回item个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _navigateTitleArr.count;
}

#pragma mark - 创建Cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView == _navigateCollection) {
        DetailKindNavigateCollectionCell *Cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"DetailKindNavigateCollectionCell" forIndexPath:indexPath];
        MoreDetailKindModel *model = _navigateTitleArr[indexPath.row];
        Cell.moreDetailKindModel = model;
        Cell.titleLabel.userInteractionEnabled = YES;
        Cell.colorView.userInteractionEnabled = YES;
        if (indexPath.item == _currentIndex) {
            
            Cell.titleLabel.textColor = [UIColor redColor];
            Cell.colorView.backgroundColor = [UIColor redColor];
            
        }else {
            
            Cell.titleLabel.textColor = [UIColor blackColor];
            Cell.colorView.backgroundColor = RGBA(233, 231, 228, 1);
            
        }
        return Cell;
    }
    if (collectionView == _bigCollection) {
        if (indexPath.row == 0) {
            BigDetailKindCollectionCell *Cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"BigDetailKindCollectionCell" forIndexPath:indexPath];
            Cell.arrModel = [NSMutableArray arrayWithArray:_arrModel];
            Cell.scrollArr = [NSMutableArray arrayWithArray:_picArr];
            Cell.navArr = [NSMutableArray arrayWithArray:_navigateArr];
            Cell.topArr = [NSMutableArray arrayWithArray:_topArr];
            Cell.delegate = self;
            return Cell;
        }
        else {
            BIgDetailKindCollectOtherCell *Cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"BIgDetailKindCollectOtherCell" forIndexPath:indexPath];
            
            MoreDetailKindModel *model = _navigateArr[indexPath.row - 1];
            NSString *Cid = [NSString stringWithFormat:@"%@", model.category_id];
            [Cell sendBigKindOtherCellWithName:model.tname Cid:Cid];
            Cell.delegate = self;
            return Cell;
        }
    }
    if (collectionView == _moreCollection) {
        SmallDetailKindCollectionCellS *Cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SmallDetailKindCollectionCellS" forIndexPath:indexPath];
        MoreDetailKindModel *model = _navigateTitleArr[indexPath.row];
        Cell.moreDetailKindModel = model;
        if (indexPath.item == _moreCurrentIndex) {
            
            Cell.titlelabel.backgroundColor = [UIColor redColor];
            Cell.titlelabel.textColor = [UIColor whiteColor];
            
        }else {
            
            Cell.titlelabel.backgroundColor = RGBA(242, 246, 248, 1);
            Cell.titlelabel.textColor = [UIColor blackColor];
        }
        
        return Cell;
    }
    return nil;
}

#pragma mark - collectionView头视图
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if (collectionView == _moreCollection) {
        if (kind == UICollectionElementKindSectionHeader) {
            BigDetailKindHeaderView *header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"BigDetailKindHeaderView" forIndexPath:indexPath];
            header.titlelabel.text = @"♦️类别";
            header.moreButton.hidden = YES;
            return header;
        }
    }
    return nil;
}

#pragma mark - collectionView头视图大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    if (collectionView == _moreCollection) {
        return CGSizeMake(SCREEN_WIDTH, 70);
    }
    return CGSizeMake(0, 0);
}

#pragma mark - bigCollectionViewCell代理方法
- (void)pushNextViewControllerWithHttpId:(NSString *)http {
    
    WJCollectionViewController *WJVc = [[WJCollectionViewController alloc] init];
    WJVc.str = http;
    [self.navigationController pushViewController:WJVc animated:YES];
    
}

- (void)pushNextDetailViewControllerWithHttpId:(NSString *)http {
    WJCollectionViewController *WJVc = [[WJCollectionViewController alloc] init];
    WJVc.str = http;
    [self.navigationController pushViewController:WJVc animated:YES];
}

- (void)clickButtonWithCurrentId:(NSString *)currentId TagName:(NSString *)tagName{
    DetailKindMoreController *detailVc = [[DetailKindMoreController alloc] init];
    self.navigationController.navigationBar.translucent = NO;
    detailVc.httpId = self.httpId;
    detailVc.tagName = tagName;
    [self.navigationController pushViewController:detailVc animated:YES];
}

- (void)contentOffSetWithCurrentIndex:(NSInteger)currentIndex {
    
    _currentIndex = currentIndex + 1;
    [UIView animateWithDuration:0.3 animations:^{
        _bigCollection.contentOffset = CGPointMake(WIDTH * _currentIndex, 0);
    }];

}

- (void)top50PushNextVcWithContryType:(NSNumber *)contryType Key:(NSString *)key isKind:(NSInteger)isKind {
    JGRankingVC *JVc = [[JGRankingVC alloc] init];
    JVc.contentType = contryType;
    JVc.key = key;
    JVc.isKind = isKind;
    self.navigationController.navigationBar.translucent = YES;
    [self.navigationController pushViewController:JVc animated:YES];
}

#pragma mark - CollectionView点击方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (collectionView == _navigateCollection) {
        DetailKindNavigateCollectionCell *cell =  (DetailKindNavigateCollectionCell *)[collectionView cellForItemAtIndexPath:indexPath];
        
        cell.titleLabel.textColor = [UIColor redColor];
        cell.colorView.backgroundColor = [UIColor redColor];
        
        /** 获取之前Cell坐标 */
        NSIndexPath *index = [NSIndexPath indexPathForItem:_currentIndex inSection:0];
        
        DetailKindNavigateCollectionCell *upCell =  (DetailKindNavigateCollectionCell *)[collectionView cellForItemAtIndexPath:index];
        upCell.titleLabel.textColor = [UIColor blackColor];
        upCell.colorView.backgroundColor = RGBA(233, 231, 228, 1);
        
        _currentIndex = indexPath.item;
        
        [UIView animateWithDuration:0.3 animations:^{
            _bigCollection.contentOffset = CGPointMake(WIDTH * _currentIndex, 0);
        }];
    }
    if (collectionView == _moreCollection) {
        SmallDetailKindCollectionCellS *Cell1 = (SmallDetailKindCollectionCellS *)[collectionView  cellForItemAtIndexPath:indexPath];
        Cell1.titlelabel.backgroundColor = [UIColor redColor];
        Cell1.titlelabel.textColor = [UIColor whiteColor];
        
        NSIndexPath *index = [NSIndexPath indexPathForItem:_moreCurrentIndex inSection:0];
        SmallDetailKindCollectionCellS *Cell2 = (SmallDetailKindCollectionCellS *)[collectionView cellForItemAtIndexPath:index];
        Cell2.titlelabel.backgroundColor = RGBA(242, 246, 248, 1);
        Cell2.titlelabel.textColor = [UIColor blackColor];
        _moreCurrentIndex = indexPath.item;
        [UIView animateWithDuration:0.3 animations:^{
            _bigCollection.contentOffset = CGPointMake(WIDTH * _moreCurrentIndex, 0);
        }];
        
    }
}


#pragma mark - KVO监听
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    CGPoint p = _bigCollection.contentOffset;
    NSInteger conut = p.x / WIDTH;
    
    if (conut > - 1 && conut < _navigateTitleArr.count - 1) {
        
        [_navigateCollection scrollRectToVisible:CGRectMake((conut - 1) * ( SCREEN_WIDTH / 4)  , 0, SCREEN_WIDTH - 81, 40) animated:YES];
        
    }
    
    _currentIndex = conut;
    [_navigateCollection reloadData];
}


#pragma mark - 数据解析
- (void)dataHandel {
    
    NSString *http = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/discovery/v2/category/recommends?categoryId=%@&contentType=album&device=android&scale=2&version=4.3.20.14", self.httpId];
    [APPTools GETWithURL:http par:nil success:^(id responseObject) {
        
        /** 导航栏数据 */
        NSDictionary *tags = responseObject[@"tags"];
        for (NSDictionary *dic in tags[@"list"]) {
            MoreDetailKindModel *model = [[MoreDetailKindModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.navigateArr addObject:model];
            [self.navigateTitleArr addObject:model];
        }
        
        /** Cell数据 */
        NSDictionary *categoryContents = responseObject[@"categoryContents"];
        for (NSDictionary *dic in categoryContents[@"list"]) {
            if ([dic[@"moduleType"] isEqualToNumber:@2]) {
                CellDetailTopKindModel *model = [[CellDetailTopKindModel alloc] init];
                NSDictionary *dic1 = [NSDictionary dictionaryWithDictionary:dic[@"list"][0]];
                [model setValuesForKeysWithDictionary:dic1];
                [self.topArr addObject:model];
            }
            if (![dic[@"moduleType"] isEqualToNumber:@2]) {
                CellDetailKindModel *model = [[CellDetailKindModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [self.arrModel addObject:model];
            }
        }
        
        /** 轮播图数据 */
        NSDictionary *focusImages = responseObject[@"focusImages"];
        for (NSDictionary *dic in focusImages[@"list"]) {
            [self.picArr addObject:dic[@"pic"]];
        }
        
        [self createSubViews];
        [self createMoreView];
        
    } filed:^(NSError *error) {
        
    }];
    
}

- (void)viewDidDisappear:(BOOL)animated {
    self.navigationController.navigationBar.translucent = YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
